<template>
  <div>
    <!-- :disabled="role == 2 ? false : true" -->
    <el-button type="primary" @click="kaikai" v-addadmindirective="role">
      添加管理员
      <el-icon class="el-icon--right">
        <Plus />
      </el-icon>
    </el-button>

    <!-- table 数据 -->

    <el-table :data="zongData" style="width: 100%">
      <el-table-column label="序号" width="180">
        <template #default="scope">
          <div style="display: flex; flex-direction: column; align-items: center">
            <span style="margin-left: 10px">{{ scope.$index + 1 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="180">
        <template #default="scope">
          <div>{{ scope.row.adminname }}</div>
        </template>
      </el-table-column>
      <el-table-column label="权限" width="180">
        <template #default="scope">
          <el-tag class="ml-2" :type="scope.row.role == 1 ? '' : 'success'">{{
              scope.row.role == 1 ? "管理员" : "超级管理员"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer v-model="drawer2" title="添加管理员">
      <template #default>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="60px" class="demo-ruleForm"
          :size="formSize" status-icon>
          <el-form-item label="账号" prop="adminname">
            <el-input v-model="ruleForm.adminname" :disabled="showbtntype == 1 ? false : true" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="ruleForm.role" placeholder="请输入角色">
              <el-option label="管理员" value="1" />
              <el-option label="超级管理员" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-tree ref="treeRef" :data="treeData" show-checkbox default-expand-all node-key="path" highlight-current
              :props="defaultProps" :default-checked-keys="ccc" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" v-if="showbtntype == 1" @click="addc">添加</el-button>
          <el-button type="primary" v-if="showbtntype == 2" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分页布局代码 -->
    <el-pagination background layout="prev, pager, next" v-model:current-page="currentpage" :total="tableData.length" />
  </div>
</template>

<script>
// import { ElMessageBox } from "element-plus";
import { CopyDocument, Plus } from "@element-plus/icons-vue";
import { Timer } from "@element-plus/icons-vue";
import { getadminlist, addadmin, editadmin, deladmin } from "@/api/http";
import router from "@/router";
//导入loadsh 这个js的工具包
import { cloneDeep } from "lodash";
// import { clone } from "lodash-es";
import { mapState } from "vuex";
//数据都是映射到计算属性上,方法都是映射到 methods上
console.log(router);
export default {
  name: "",
  data() {
    return {
      // role: "",
      tableData: [],
      drawer2: false,
      ruleForm: {
        adminname: "",
        password: "",
        role: "",
        checkedKeys: [],
      },
      rules: {
        adminname: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
      data: [],
      ccc: [],
      showbtntype: 1, //显示按钮的状态
      currentpage: 1, //当前页
    };
  },
  computed: {
    ...mapState(["role"]),
    treeData() {
      // let newArr = router.options.routes[1].children.map((item) => {
      //   return { label: item.label, children: item.children };
      // });
      // return newArr;
      // console.log("路由配置表", router.options.routes[1].children);

      let newroutes = cloneDeep(router.options.routes[1].children);
      console.log(321, newroutes);
      newroutes[1].children.pop();
      //返回的值为深拷贝后的路由表，该路由表已经被修改过了，删掉了添加轮播图的路由
      return newroutes;
    },
    zongData() {
      return this.tableData.slice(
        (this.currentpage - 1) * 10,
        this.currentpage * 10
      );
    },
  },
  watch: {
    showbtntype(newvalue) {
      if (newvalue == 1) {
        this.rules.adminname[0].required = true;
      } else {
        this.rules.adminname[0].required = false;
      }
    },
  },
  components: {
    Plus,
    Timer,
  },
  created() {
    this.getlist();
  },
  methods: {
    getlist() {
      getadminlist().then((res) => {
        console.log(111, res);
        this.tableData = res.data.data;
      });
    },
    kaikai() {
      this.drawer2 = true;
      this.ruleForm.adminname = "";
      this.ruleForm.password = "";
      this.ruleForm.role = "";
      // console.log(55555, this.$refs.treeRef);
      if (this.$refs.treeRef) {
        // console.log(111111111111, $refs);
        this.$refs.treeRef.setCheckedKeys([]);
      }
      this.showbtntype = 1;
    },
    cancelClick() { },
    //f封装的获取树形菜单的选中项
    fengqude() {
      // console.log(this.ruleForm);
      // console.log(this.$refs.treeRef.getCheckedNodes(true));
      // this.ruleForm.checkedkeys= this.$refs.treeRef.getCheckedNodes()
      // console.log(this.treeData);
      //第一步：根据选择中的子菜单，找到选中的富集菜单项
      let list = this.$refs.treeRef.getCheckedNodes(true);
      let template = []; //临时数组用来去掉重复项的
      let result = []; //最终的数组
      list.forEach((item) => {
        const parent = this.treeData.find((item1) => {
          return item1.children.some((item2) => item2.label == item.label);
        });
        if (!template.includes(parent.label)) {
          template.push(parent.label);

          result.push({
            label: parent.label,
            path: parent.path,
            children: [item],
          });
        } else {
          result.find((v) => v.label == parent.label).children.push(item);
        }
      });

      // console.log(result);
      this.ruleForm.checkedKeys = result;
    },
    // 添加的确认
    addc() {
      this.fengqude();
      if (
        this.ruleForm.adminname != "" &&
        this.ruleForm.password != "" &&
        this.ruleForm.role != "" &&
        this.ruleForm.checkedKeys.length != 0
      ) {
        //调用添加用户接口
        addadmin(this.ruleForm).then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            this.getlist();
            this.drawer2 = false;
          }
        });
      } else {
        ElMessage({
          message: "请完善用户信息",
          type: "warning",
        });
      }
    },

    handleEdit(index, row) {
      this.drawer2 = true;
      this.ruleForm.adminname = row.adminname;
      this.ruleForm.password = row.password;
      this.ruleForm.role = row.role;
      let checkArr = [];
      row.checkedKeys.forEach((item) => {
        item.children.forEach((item1) => {
          checkArr.push(item1.path);
        });
      });
      if (this.$refs.treeRef) {
        this.$refs.treeRef.setCheckedKeys([]);
      }
      console.log(123233, checkArr);
      this.ccc = checkArr;
      this.showbtntype = 2;
    },
    confirmClick() {
      //调用获取所有的属性菜单选中项的方法
      this.fengqude();
      if (
        this.ruleForm.adminname != "" &&
        this.ruleForm.password != "" &&
        this.ruleForm.role != "" &&
        this.ruleForm.checkedKeys.length != 0
      ) {
        //调用编辑用户接口
        editadmin(this.ruleForm).then((res) => {
          if (res.data.code == 200) {
            //隐藏抽屉
            this.drawer2 = false;
            //重新获取管理列表数据
            this.getlist();
          }
        });
      } else {
        ElMessage({
          message: "请完善编辑用户信息",
          type: "warning",
        });
      }
    },
    handleDelete(index, row) {
      deladmin({ adminid: row.adminid }).then((res) => {
        if (res.data.code == 200) {
          //重新获取管理列表数据
          this.getlist();
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-table {
  margin-top: 20px;
}
</style>